package com.pgy.general.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pgy.general.annotation.PassToken;
import com.pgy.general.entity.Document;
import com.pgy.general.entity.User;
import com.pgy.general.exceptions.LoginRuntimeException;
import com.pgy.general.mapper.DocumentMapper;
import com.pgy.general.result.RetResponse;
import com.pgy.general.result.RetResult;
import com.pgy.general.service.IDocumentService;
import com.pgy.general.service.IUserService;
import com.pgy.general.util.FileUtil;
import com.pgy.general.util.TokenUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Cc
 * @since 2021-03-22
 */
@RestController
@RequestMapping("/document")
@Api(tags ="文件接口")
public class DocumentController {
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IDocumentService iDocumentService;
    @Autowired
    private DocumentMapper documentMapper;

    //上传文件

    @ApiOperation(value = "/upfile", notes = "用户上传文件", httpMethod = "POST")
    @PostMapping("/upfile")
    public RetResult upfile( MultipartFile file, HttpServletRequest request , String fileName){
        String userId = TokenUtil.getUserByToken(request);
        User user = iUserService.queryById(userId);
        if (user==null){
            throw new LoginRuntimeException("登录超时，请重新登录！");
        }
        String filePath = FileUtil.upFile(file,user.getId().toString());
        Document document=new Document();
        document.setFilepath(filePath);
        document.setFilename(fileName);
        document.setUserid(user.getId());
        document.setCreatetime(new Date());
        document.setName(user.getName());
        boolean save = iDocumentService.save(document);
        if (save){
            return RetResponse.makeOKRsp();
        }
        return RetResponse.makeErrRsp();
    }
    @ApiOperation(value = "/querybyuseridfilename", notes = "通过用户id查询该用户所有文件或者文件名字查询文件", httpMethod = "POST")
    @PostMapping("/querybyuseridfilename")
    public RetResult querybyuseridfilename(Integer userid, HttpServletRequest request, String filename,
                                   @ApiParam(value = "当前页，不传则默认为第一页") @RequestParam(required = false,defaultValue = "1") Integer currentPage,
                                   @ApiParam(value = "每页显示条数，不传默认每页20条") @RequestParam(required = false,defaultValue = "20") Integer size){
        QueryWrapper<Document> queryWrapper= Wrappers.<Document> query();
        queryWrapper.orderByDesc("createTime");
        queryWrapper.eq("userid",userid);
        queryWrapper.isNull("deleteTime");
        if(filename!=null && filename!=""){
            queryWrapper.like("fileName",filename);
        }
        Page<Document> page =documentMapper.selectPage(new Page<Document>(currentPage,size),queryWrapper);
        return RetResponse.makeOKRsp(page);
    }

    @ApiOperation(value = "/queryallfile", notes = "查询所有用户所有文件", httpMethod = "POST")
    @PostMapping("/queryallfile")
    public RetResult queryallfile( HttpServletRequest request, String filename,
                                   @ApiParam(value = "当前页，不传则默认为第一页") @RequestParam(required = false,defaultValue = "1") Integer currentPage,
                                   @ApiParam(value = "每页显示条数，不传默认每页20条") @RequestParam(required = false,defaultValue = "20") Integer size){
        QueryWrapper<Document> queryWrapper= Wrappers.<Document> query();
        queryWrapper.orderByDesc("createTime");
        queryWrapper.isNull("deleteTime");
        if(filename!=null && filename!=""){
            queryWrapper.like("fileName",filename);
        }
        Page<Document> page =documentMapper.selectPage(new Page<Document>(currentPage,size),queryWrapper);
        return RetResponse.makeOKRsp(page);
    }



    @ApiOperation(value = "删除指定id文件", notes = "删除指定id文件", httpMethod = "POST")
    @PostMapping("/deletebyuserid")
    public RetResult deletebyuserid(Integer id,HttpServletRequest request){
        Document document=new Document();
        document.setId(id);
        document.setDeletetime(new Date());
        boolean b = iDocumentService.saveOrUpdate(document);
        if (b){
            return RetResponse.makeOKRsp();
        }
        return RetResponse.makeErrRsp();
    }

    @ApiOperation(value = "/queryfilebyid", notes = "通过文件id查询文件（该接口可忽略）", httpMethod = "POST")
    @PostMapping("/queryfilebyid")
    public RetResult queryfilebyid(Integer id, HttpServletRequest request){

        Document document = iDocumentService.getById(id);
        return RetResponse.makeOKRsp(document);
    }





}
